/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Presentacion;


import ModeloLogicoSistema.AdministradorCliente;
import ModeloLogicoSistema.AdministradorOrden;
import ModeloLogicoSistema.AdministradorServicio;
import ModeloLogicoSistema.Cliente;
import ModeloLogicoSistema.Imprimir_ticket;
import ModeloLogicoSistema.Orden;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import ModeloLogicoSistema.Servicio;
import ModeloLogicoSistema.ServicioContratado;
import ModeloLogicoSistema.ServicioEspecialContratado;
import ModeloLogicoSistema.Servicio.TipoServicio;
import ModeloLogicoSistema.Validacion;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
import javax.swing.JOptionPane;

/**
 *
 * @author debo
 */
public class AltaOrden extends javax.swing.JDialog {

    private String primerDia;
    private String segundoDia;
    private String tercerDia;
    private String cuartoDia;
    private String quintoDia;
    private String sextoDia;
    private String septimoDia;
    private String octavoDia;
    private AdministradorCliente administradorClientes = null;
    private AdministradorServicio administradorServicio = null;
    private AdministradorOrden administradorOrden = null;
    private Integer ultimoCodCliente = null;
    private ArrayList<Servicio> servicios = new ArrayList<>();
    private SimpleDateFormat formateador = new SimpleDateFormat("dd/MM/yyyy");
    private Calendar calendario = new GregorianCalendar();
    private Cliente cliente;
    private ArrayList<ServicioEspecialContratado> serviciosEspeciales = new ArrayList<>();
    private AltaOrden _this;
    private Integer porcentajeDescuento;
    private String observaciones;
    private int valets = 0, planchados = 1;
    private int inicio = 0; //Para las tablas primera fila o columna
    private int indiceSubtotal=0;
    private int indiceDescuento=1;
    private int indiceTotal=2;
    private int indiceSenia=3;
    private int indiceSaldo=4;
    
    private void cargarServiciosEnLaTabla(List<Servicio> servicios) {
        cbServicios.addItem("Servicio Especial");
        ListIterator it = servicios.listIterator();
        while (it.hasNext()) {
            Servicio s = (Servicio) it.next();
            cbServicios.addItem(s.getNombre());
        }

    }

    public String getFechaOrden() {
        DateFormat dateFormat;
        dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        Calendar cal = Calendar.getInstance();
        String diahora = dateFormat.format(cal.getTime());
        String fecha = diahora.substring(0, 10);
        return fecha;
    }

    private void cargarFechas() {
        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        Calendar cal = Calendar.getInstance();
        String diahora = dateFormat.format(cal.getTime());
        String fecha = diahora.substring(0, 10);
        String hora = diahora.substring(11);
        txtFecha.setText(fecha);
        txtHora.setText(hora);
        Calendar hoy = Calendar.getInstance();

        txtFecha.setEditable(false);
        Date ahora = new Date();
        formateador.format(ahora);
        this.jDateChooser1.setMinSelectableDate(ahora);
    }

    private void iniciarComponentes() {
        this.txtApellido.setVisible(false);
        this.labelApellido.setVisible(false);
        this.txtNombre.setVisible(false);
        this.labelNombre.setVisible(false);
        this.jLabel10.setVisible(false);
        this.labelDireccion.setVisible(false);
        this.labelTel.setVisible(false);
        this.labelCel.setVisible(false);
        this.txtDir.setVisible(false);
        this.txtTel.setVisible(false);
        this.txtCel.setVisible(false);
        this.labelAlertaCliente.setVisible(false);
        this.setSize(740, 720);
        this.setLocationRelativeTo(null);
        try {
            this.administradorClientes = new AdministradorCliente();
            this.ultimoCodCliente = this.administradorClientes.nuevoCodigoCliente();
        } catch (SQLException ex) {
            Logger.getLogger(AltaOrden.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            administradorServicio = new AdministradorServicio();
            servicios = administradorServicio.getListaservicios();
            if (servicios.isEmpty()) {
                cbServicios.addItem("No se han cargado servicios");
            }
            administradorOrden = new AdministradorOrden();
        } catch (SQLException ex) {
            Logger.getLogger(AltaOrden.class.getName()).log(Level.SEVERE, null, ex);
        }
        cargarServiciosEnLaTabla(servicios);
        try {
            idO.setText(this.administradorOrden.nuevoCodigoOrden().toString());
            idO.setEditable(false);
        } catch (SQLException ex) {
            idO.setText("0");
        }
        this.jSpinner2.setVisible(false);
        this.tablaTotalPendientes.setValueAt('0', 0, this.valets);
        this.tablaTotalPendientes.setValueAt('0', 0, this.planchados);
        //this.txtValets.setText("0");
        //this.txtPlanchado.setText("0");
        iniciarTablaMontos();

    }

    private void iniciarTablaMontos() {

        for (int i = 0; i < tablaMontos.getColumnCount(); i++) {
            tablaMontos.setValueAt(0, 0, i);
        }
    }

    private void cargarTablaPendientes() {
        Calendar cal = Calendar.getInstance();
        primerDia = formateador.format(cal.getTime());
        cal.add(Calendar.DATE, 1);
        segundoDia = formateador.format(cal.getTime());
        cal.add(Calendar.DATE, 1);
        tercerDia = formateador.format(cal.getTime());
        cal.add(Calendar.DATE, 1);
        cuartoDia = formateador.format(cal.getTime());
        cal.add(Calendar.DATE, 1);
        quintoDia = formateador.format(cal.getTime());
        cal.add(Calendar.DATE, 1);
        sextoDia = formateador.format(cal.getTime());
        cal.add(Calendar.DATE, 1);
        septimoDia = formateador.format(cal.getTime());
        cal.add(Calendar.DATE, 1);
        octavoDia = formateador.format(cal.getTime());
        tablaPendientes.setValueAt(TipoServicio.Planchado.toString(), 0, 0);
        tablaPendientes.setValueAt(TipoServicio.Valets.toString(), 1, 0);
        tablaPendientes.setValueAt("Deliverys", 2, 0);


        DefaultTableModel tableModel = (DefaultTableModel) tablaPendientes.getModel();
        String dias[] = {"Pendientes", primerDia, segundoDia, tercerDia,
            cuartoDia, quintoDia, sextoDia, septimoDia, octavoDia};
        tableModel.setColumnIdentifiers(dias);
        cargarPendientes();
        tablaPendientes.setModel(tableModel);
    }

    public AltaOrden(java.awt.Frame parent, boolean modal) throws SQLException {
        super(parent, modal);
        initComponents();
        _this = this;
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent we) {
                int eleccion = JOptionPane.showConfirmDialog(null, "Si cierra esta ventana perderá cualquier dato que haya ingresado. ¿Aun desea cerrar?", "Advertencia", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);

                if (eleccion == JOptionPane.YES_OPTION) {

                    _this.dispose();
                }
            }
        });
        iniciarComponentes();
        cargarFechas();
        cargarTablaPendientes();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jDialog1 = new javax.swing.JDialog();
        btnObservaciones = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        idO = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtFecha = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtHora = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel4 = new javax.swing.JLabel();
        cbServicios = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaServicio = new javax.swing.JTable();
        jButton4 = new javax.swing.JButton();
        jBtnRegistrar = new javax.swing.JButton();
        jBtnLimpiar = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        tablaMontos = new javax.swing.JTable();
        jRBtnDelivery = new javax.swing.JRadioButton();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        txtIDcliente = new javax.swing.JTextField();
        jBtnBuscarCliente = new javax.swing.JButton();
        jBtnAgregarCliente = new javax.swing.JButton();
        labelCliente = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        txtApellido = new javax.swing.JTextField();
        labelNombre = new javax.swing.JLabel();
        labelApellido = new javax.swing.JLabel();
        jSeparator2 = new javax.swing.JSeparator();
        labelAlertaCliente = new javax.swing.JLabel();
        labelDireccion = new javax.swing.JLabel();
        labelTel = new javax.swing.JLabel();
        txtDir = new javax.swing.JTextField();
        txtTel = new javax.swing.JTextField();
        labelCel = new javax.swing.JLabel();
        txtCel = new javax.swing.JTextField();
        jBtnAgregarServicio = new javax.swing.JButton();
        BtnQuitar = new javax.swing.JButton();
        labelCantidad = new javax.swing.JLabel();
        spinnerCantidad = new javax.swing.JSpinner();
        jSeparator3 = new javax.swing.JSeparator();
        jDateChooser1 = new com.toedter.calendar.JDateChooser();
        jLabel10 = new javax.swing.JLabel();
        jSpinner1 = new javax.swing.JSpinner();
        jSpinner2 = new javax.swing.JSpinner();
        btnAbona = new javax.swing.JButton();
        jScrollPane5 = new javax.swing.JScrollPane();
        tablaPendientes = new javax.swing.JTable();
        labelErrorServicio = new javax.swing.JLabel();
        labelErrorServicio.setVisible(false);
        jButton1 = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        txtAreaObservaciones = new javax.swing.JTextArea();
        labelObservaciones = new javax.swing.JLabel();
        jScrollPane6 = new javax.swing.JScrollPane();
        tablaTotalPendientes = new javax.swing.JTable();

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jTable2);

        javax.swing.GroupLayout jDialog1Layout = new javax.swing.GroupLayout(jDialog1.getContentPane());
        jDialog1.getContentPane().setLayout(jDialog1Layout);
        jDialog1Layout.setHorizontalGroup(
            jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jDialog1Layout.setVerticalGroup(
            jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        btnObservaciones.setText("Observaciones");
        btnObservaciones.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnObservacionesActionPerformed(evt);
            }
        });

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Alta de Orden");
        setResizable(false);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel5.setText("IDOrden");

        idO.setEditable(false);
        idO.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                idOActionPerformed(evt);
            }
        });

        jLabel3.setLabelFor(txtHora);
        jLabel3.setText("Hora");

        txtFecha.setEditable(false);
        txtFecha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtFechaActionPerformed(evt);
            }
        });

        jLabel2.setText("Fecha");

        txtHora.setEditable(false);
        txtHora.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtHoraActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(idO, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 431, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(18, 18, 18)
                                .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(18, 18, 18)
                                .addComponent(txtHora, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(idO, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtHora, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 720, 80));

        jLabel4.setText("Servicios");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 330, 70, 20));

        cbServicios.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbServiciosActionPerformed(evt);
            }
        });
        getContentPane().add(cbServicios, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 330, 159, -1));

        tablaServicio.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Servicio", "Precio", "Cantidad", "Subtotal"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Double.class, java.lang.Integer.class, java.lang.Double.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, true, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaServicio.setColumnSelectionAllowed(true);
        tablaServicio.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(tablaServicio);
        tablaServicio.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tablaServicio.getColumnModel().getColumn(0).setPreferredWidth(250);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 370, -1, 109));

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/cancelar.png"))); // NOI18N
        jButton4.setText("Cerrar");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(590, 660, 110, -1));

        jBtnRegistrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Guardar.png"))); // NOI18N
        jBtnRegistrar.setText("Registrar");
        jBtnRegistrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnRegistrarActionPerformed(evt);
            }
        });
        getContentPane().add(jBtnRegistrar, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 660, 120, -1));

        jBtnLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/limpiar.png"))); // NOI18N
        jBtnLimpiar.setText("Limpiar");
        jBtnLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnLimpiarActionPerformed(evt);
            }
        });
        getContentPane().add(jBtnLimpiar, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 660, 110, -1));

        tablaMontos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null}
            },
            new String [] {
                "SUBTOTAL", "DESCUENTO", "TOTAL", "SEÑA", "SALDO"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaMontos.setColumnSelectionAllowed(true);
        tablaMontos.getTableHeader().setReorderingAllowed(false);
        tablaMontos.addInputMethodListener(new java.awt.event.InputMethodListener() {
            public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
                tablaMontosInputMethodTextChanged(evt);
            }
            public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
            }
        });
        tablaMontos.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tablaMontosKeyPressed(evt);
            }
        });
        jScrollPane3.setViewportView(tablaMontos);
        tablaMontos.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);

        getContentPane().add(jScrollPane3, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 500, 350, 44));

        jRBtnDelivery.setText("Delivery");
        jRBtnDelivery.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRBtnDeliveryActionPerformed(evt);
            }
        });
        getContentPane().add(jRBtnDelivery, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 580, -1, -1));

        jLabel6.setText("Fecha de Entrega:");
        jLabel6.setToolTipText("");
        getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 570, 100, 20));

        jLabel7.setText("Entrega Desde");
        getContentPane().add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 570, 90, -1));

        txtIDcliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtIDclienteActionPerformed(evt);
            }
        });

        jBtnBuscarCliente.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Buscar.png"))); // NOI18N
        jBtnBuscarCliente.setText("Buscar");
        jBtnBuscarCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnBuscarClienteActionPerformed(evt);
            }
        });

        jBtnAgregarCliente.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Add Client.png"))); // NOI18N
        jBtnAgregarCliente.setText("Agregar");
        jBtnAgregarCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnAgregarClienteActionPerformed(evt);
            }
        });

        labelCliente.setText("IDCliente");

        txtNombre.setEditable(false);

        txtApellido.setEditable(false);

        labelNombre.setLabelFor(txtNombre);
        labelNombre.setText("Nombre");

        labelApellido.setText("Apellido");

        labelAlertaCliente.setForeground(new java.awt.Color(255, 0, 0));
        labelAlertaCliente.setText("El campo Cliente es obligatorio");

        labelDireccion.setText("Dirección");

        labelTel.setText("Teléfono");

        txtDir.setEditable(false);

        txtTel.setEditable(false);

        labelCel.setText("Celular");

        txtCel.setEditable(false);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(labelCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtIDcliente, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jBtnBuscarCliente, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jBtnAgregarCliente, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(labelNombre)
                            .addComponent(labelApellido))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtApellido, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(26, 26, 26)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(labelCel, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtCel, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(labelTel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(labelDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtTel)
                                    .addComponent(txtDir))))))
                .addGap(22, 22, 22))
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelAlertaCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelCliente)
                    .addComponent(txtIDcliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBtnAgregarCliente)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelNombre)
                    .addComponent(txtDir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelDireccion))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(labelApellido)
                        .addComponent(jBtnBuscarCliente)
                        .addComponent(txtApellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(labelTel))
                    .addComponent(txtTel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelAlertaCliente)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(labelCel)
                            .addComponent(txtCel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        getContentPane().add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 100, 730, 110));

        jBtnAgregarServicio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/agregarServicio.png"))); // NOI18N
        jBtnAgregarServicio.setText("Agregar");
        jBtnAgregarServicio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnAgregarServicioActionPerformed(evt);
            }
        });
        jBtnAgregarServicio.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jBtnAgregarServicioFocusGained(evt);
            }
        });
        getContentPane().add(jBtnAgregarServicio, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 330, 100, -1));

        BtnQuitar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/quitar.png"))); // NOI18N
        BtnQuitar.setText("Quitar");
        BtnQuitar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnQuitarActionPerformed(evt);
            }
        });
        getContentPane().add(BtnQuitar, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 330, 110, -1));

        labelCantidad.setText("Cantidad");
        getContentPane().add(labelCantidad, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 330, -1, 20));

        spinnerCantidad.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1)));
        spinnerCantidad.setName(""); // NOI18N
        spinnerCantidad.setValue(1);
        getContentPane().add(spinnerCantidad, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 330, 50, -1));
        getContentPane().add(jSeparator3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 550, 710, 10));

        jDateChooser1.setDateFormatString("dd/MM/yyyy");
        jDateChooser1.setMinSelectableDate(new java.util.Date(-62135755136000L));
        jDateChooser1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jDateChooser1FocusGained(evt);
            }
        });
        getContentPane().add(jDateChooser1, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 570, 120, -1));

        jLabel10.setText("Entrega hasta");
        getContentPane().add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 600, 90, -1));

        jSpinner1.setModel(new javax.swing.SpinnerNumberModel(8, 8, 21, 1));
        jSpinner1.setValue(8);
        getContentPane().add(jSpinner1, new org.netbeans.lib.awtextra.AbsoluteConstraints(510, 570, 50, -1));

        jSpinner2.setModel(new javax.swing.SpinnerNumberModel(8, 8, 21, 1));
        getContentPane().add(jSpinner2, new org.netbeans.lib.awtextra.AbsoluteConstraints(510, 600, 50, -1));

        btnAbona.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/seña.png"))); // NOI18N
        btnAbona.setText("Seña");
        btnAbona.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAbonaActionPerformed(evt);
            }
        });
        getContentPane().add(btnAbona, new org.netbeans.lib.awtextra.AbsoluteConstraints(620, 490, 110, -1));

        tablaPendientes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null}
            },
            new String [] {
                "", "", "", "", "null", "null", "null", "null", "Title 9"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaPendientes.getTableHeader().setReorderingAllowed(false);
        jScrollPane5.setViewportView(tablaPendientes);
        tablaPendientes.getColumnModel().getColumn(0).setPreferredWidth(130);

        getContentPane().add(jScrollPane5, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 220, 720, 100));

        labelErrorServicio.setForeground(new java.awt.Color(255, 0, 0));
        labelErrorServicio.setText("Debe seleccionarse al menos un servicio para registrar la orden");
        getContentPane().add(labelErrorServicio, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 480, 450, 20));

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/descuento.png"))); // NOI18N
        jButton1.setText("Descuento");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(620, 520, 110, -1));

        txtAreaObservaciones.setColumns(1);
        txtAreaObservaciones.setLineWrap(true);
        txtAreaObservaciones.setRows(1);
        txtAreaObservaciones.setWrapStyleWord(true);
        txtAreaObservaciones.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtAreaObservacionesKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtAreaObservacionesKeyTyped(evt);
            }
        });
        jScrollPane4.setViewportView(txtAreaObservaciones);

        getContentPane().add(jScrollPane4, new org.netbeans.lib.awtextra.AbsoluteConstraints(554, 370, 160, 110));

        labelObservaciones.setText("Observaciones:");
        getContentPane().add(labelObservaciones, new org.netbeans.lib.awtextra.AbsoluteConstraints(600, 350, 100, -1));

        tablaTotalPendientes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null}
            },
            new String [] {
                "Valets", "Planchado"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                true, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaTotalPendientes.getTableHeader().setReorderingAllowed(false);
        jScrollPane6.setViewportView(tablaTotalPendientes);

        getContentPane().add(jScrollPane6, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 500, 180, 50));

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jBtnAgregarClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnAgregarClienteActionPerformed
        AltaCliente altaDeCliente = null;
        try {
            altaDeCliente = new AltaCliente(null, rootPaneCheckingEnabled);
            altaDeCliente.setVisible(true);
            if (altaDeCliente.estaRegistrado()) {
                txtIDcliente.setText(this.ultimoCodCliente.toString());
                this.cliente = administradorClientes.cargarCliente(this.ultimoCodCliente);
                this.txtApellido.setVisible(true);
                this.txtNombre.setVisible(true);
                this.labelApellido.setVisible(true);
                this.labelNombre.setVisible(true);
                this.labelDireccion.setVisible(true);
                this.labelTel.setVisible(true);
                this.labelCel.setVisible(true);
                this.txtApellido.setText(cliente.getApellido());
                this.txtNombre.setText(cliente.getNombre());
                String calle = this.cliente.getCalle();
                String nro = this.cliente.getNroCalle();
                this.txtDir.setText(calle + " " + nro);
                this.txtDir.setVisible(true);
                this.txtTel.setText(this.cliente.getTelFijo());
                this.txtCel.setText(this.cliente.getCel());
                this.txtTel.setVisible(true);
                this.txtCel.setVisible(true);
                if (this.labelAlertaCliente.isVisible()) {
                    this.labelAlertaCliente.setVisible(false);
                }
            }
            altaDeCliente.dispose();
        } catch (SQLException ex) {
            Logger.getLogger(AltaOrden.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jBtnAgregarClienteActionPerformed

    private void jBtnBuscarClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnBuscarClienteActionPerformed
        BuscarCliente buscarCliente = new BuscarCliente(null, rootPaneCheckingEnabled);
        buscarCliente.habilitarBusqueda();
        buscarCliente.setVisible(true);
        if (buscarCliente.fueAceptado()) {
            this.cliente = buscarCliente.getClienteSeleccionado();
            txtIDcliente.setText(cliente.getNroCliente().toString());
            txtNombre.setText(cliente.getNombre());
            txtApellido.setText(cliente.getApellido());
            txtDir.setText(cliente.getCalle() + " " + cliente.getNroCalle());
            txtCel.setText(cliente.getCel());
            txtTel.setText(cliente.getTelFijo());
            this.txtNombre.setVisible(true);
            this.txtApellido.setVisible(true);
            this.labelNombre.setVisible(true);
            this.labelApellido.setVisible(true);
            this.labelDireccion.setVisible(true);
            this.labelTel.setVisible(true);
            this.labelCel.setVisible(true);
            this.txtDir.setVisible(true);
            this.txtCel.setVisible(true);
            this.txtTel.setVisible(true);
            if (this.labelAlertaCliente.isVisible()) {
                this.labelAlertaCliente.setVisible(false);
            }
            buscarCliente.dispose();
        }
    }//GEN-LAST:event_jBtnBuscarClienteActionPerformed

    private void calcularMontosTablaMontos() {
        DefaultTableModel modelo = (DefaultTableModel) tablaServicio.getModel();
        int iteraciones = modelo.getRowCount(), col = modelo.getColumnCount() - 1;
        DefaultTableModel modeloMonto = (DefaultTableModel) tablaMontos.getModel();

        Double montoTotal = new Double(0), montoSubtotal=new Double(0),montoAdeudado = new Double(0), montoAbonado, descuento = new Double(0);
        try {
            montoAbonado = new Double(modeloMonto.getValueAt(0, this.indiceSenia).toString());
        } catch (Exception e) {
            montoAbonado = new Double(0);
        }
        for (int i = 0; i < iteraciones; i++) {
            montoSubtotal = montoSubtotal + (Double) modelo.getValueAt(i, col);
        }
        try {
            descuento = new Double(montoSubtotal * this.porcentajeDescuento / 100);
        } catch (Exception e) {
            descuento = new Double(0);
        }
        montoTotal=montoSubtotal-descuento;
        montoAdeudado = montoTotal - montoAbonado;
        if (montoAdeudado < 0) {
            montoAbonado = montoTotal - descuento;
            montoAdeudado = new Double(0);
            JOptionPane.showMessageDialog(null, "Se ha ajustado el valor abonado, para que corresponda con la deuda percibida", "Excede seña posible", JOptionPane.INFORMATION_MESSAGE);
        }
        modeloMonto.setValueAt(montoTotal, 0, this.indiceTotal);
        modeloMonto.setValueAt(montoAbonado, 0, this.indiceSenia);
        modeloMonto.setValueAt(descuento, 0, this.indiceDescuento);
        modeloMonto.setValueAt(montoAdeudado, 0, this.indiceSaldo);
        modeloMonto.setValueAt(montoSubtotal, 0, this.indiceSubtotal);
    }

    private void cargaServEsp(DefaultTableModel modelo, Integer cant, String nombreS) {
        try {
            Double precio = new Double(JOptionPane.showInputDialog(null, "Ingrese precio de servicio",
                    "Precio", JOptionPane.QUESTION_MESSAGE));

            Double subtotal = new Double(precio * cant);
            Object[] fila = {nombreS, precio, cant, subtotal};
            modelo.addRow(fila);
            ServicioEspecialContratado servicio = new ServicioEspecialContratado(nombreS, null, precio, cant, Integer.parseInt(this.idO.getText()));
            this.serviciosEspeciales.add(servicio);
            if (this.labelErrorServicio.isVisible()) {
                this.labelErrorServicio.setVisible(false);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "No se pudo cargar el servicio especial");
        }

    }

    private void cargarServLista(DefaultTableModel modelo, Integer cant, String nombreS) {
        ListIterator it = servicios.listIterator();
        while (it.hasNext()) {
            Servicio service = (Servicio) it.next();
            if (service.getNombre().equalsIgnoreCase(nombreS)) {
                Double subtotal = new Double(service.getPrecio() * cant);
                Object[] fila = {service.getNombre(),
                    service.getPrecio(), cant, subtotal};

                modelo.addRow(fila);
                //Modifico la cantidad que se muestra en el encabezado
                if (service.getTipoServicio().equalsIgnoreCase(TipoServicio.Valets.toString())) {
                    Integer cantidad = Integer.valueOf(this.tablaTotalPendientes.getValueAt(inicio, valets).toString());
                    if (cantidad == null) {
                        cantidad = 0;
                    }
                    cantidad = cantidad + cant;
                    this.tablaTotalPendientes.setValueAt(cantidad, inicio, valets);
                } else if (service.getTipoServicio().equalsIgnoreCase(TipoServicio.Planchado.toString())) {
                    Integer cantidad = Integer.valueOf(this.tablaTotalPendientes.getValueAt(inicio, this.planchados).toString());
                    if (cantidad == null) {
                        cantidad = 0;
                    }
                    cantidad = cantidad + cant;
                    this.tablaTotalPendientes.setValueAt(cantidad, inicio, planchados);
                }
                if (this.labelErrorServicio.isVisible()) {
                    this.labelErrorServicio.setVisible(false);
                }
            }
        }
    }

    private void setearCabecera(String nombre, Integer cant) {
        for (Servicio service : this.servicios) {
            if (service.getNombre().equalsIgnoreCase(nombre)) {
                if (service.getTipoServicio().equalsIgnoreCase(TipoServicio.Valets.toString())) {
                    Integer cantidad = Integer.valueOf(this.tablaTotalPendientes.getValueAt(inicio, valets).toString());
                    if (cantidad == null) {
                        cantidad = 0;
                    }
                    cantidad = cantidad + cant;
                    this.tablaTotalPendientes.setValueAt(cantidad, inicio, valets);
                } else if (service.getTipoServicio().equalsIgnoreCase(TipoServicio.Planchado.toString())) {
                    Integer cantidad = Integer.valueOf(this.tablaTotalPendientes.getValueAt(inicio, planchados).toString());
                    if (cantidad == null) {
                        cantidad = 0;
                    }
                    cantidad = cantidad + cant;
                    this.tablaTotalPendientes.setValueAt(cantidad, inicio, planchados);
                }

            }

        }
    }

    private ServicioEspecialContratado ServEsp(String nombreS) {
        ServicioEspecialContratado servEsp = null;
        ListIterator itSE = this.serviciosEspeciales.listIterator();
        while (itSE.hasNext()) {
            ServicioEspecialContratado servEspecial = (ServicioEspecialContratado) itSE.next();
            if (servEspecial.esElServicio(nombreS)) {
                return servEspecial;
            }
        }
        return servEsp;
    }

    private void jBtnAgregarServicioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnAgregarServicioActionPerformed
        String prefijo = "S.E.: ";
        DefaultTableModel modelo = (DefaultTableModel) tablaServicio.getModel();
        String nombreS = (String) this.cbServicios.getSelectedItem();
        ListIterator it = servicios.listIterator();
        Integer cant, cantTotal;
        cant = (Integer) this.spinnerCantidad.getValue();
        boolean servicioPedidoAnteriormente = false;
        int cantFilas = modelo.getRowCount();
        int i = 0;
        boolean servEspecial = false;
        if (nombreS.equalsIgnoreCase("Servicio Especial")) {
            String opcS = JOptionPane.showInputDialog(null, "Ingrese un nombre para el servicio especial",
                    "Nombre", JOptionPane.QUESTION_MESSAGE);
            if (opcS == null) {
                return;
            } else {
                if (opcS.equals("")) {
                    return;
                } else {
                    nombreS = prefijo + opcS;
                    servEspecial = true;
                }
            }

        }
        while (i < cantFilas & !servicioPedidoAnteriormente) {
            String nombre = modelo.getValueAt(i, 0).toString();
            if (nombre.equalsIgnoreCase(nombreS)) {
                cantTotal = (Integer) modelo.getValueAt(i, 2) + cant;
                modelo.setValueAt(cantTotal, i, 2);
                Double precio = new Double(modelo.getValueAt(i, 1).toString());
                modelo.setValueAt(precio * cantTotal, i, 3);
                servicioPedidoAnteriormente = true;
                calcularMontosTablaMontos();
                setearCabecera(nombreS, cant);
                if (servEspecial) {
                    this.ServEsp(nombreS).setCantidad(cantTotal);
                }
            }

            i++;
        }
        if (cantFilas >= 5) {
            JOptionPane.showMessageDialog(null, "Si desea ingresar más servicios, cree una nueva orden.");
            return;
        }
        if (servicioPedidoAnteriormente) {
            return;
        } else {
            if (servEspecial) {
                cargaServEsp(modelo, cant, nombreS);
            } else {
                cargarServLista(modelo, cant, nombreS);
            }
        }
        calcularMontosTablaMontos();

    }//GEN-LAST:event_jBtnAgregarServicioActionPerformed

    private void jBtnRegistrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnRegistrarActionPerformed
        //Revisar que estas lineas de codigo no moleten las fechas luego 
        //de la primer invocacion
        String fechaPactada;
        try {
            Date fecha = this.jDateChooser1.getDate();

            calendario.setTime(fecha);
            fechaPactada = formateador.format(calendario.getTime());

        } catch (Exception e) {
            // this.labelAlertaFecha.setVisible(true);
            JOptionPane.showMessageDialog(null, "No ha ingresado una fecha de entrega");
            return;
        }

        Integer codOrden = new Integer(idO.getText());
        Integer codCliente;
        try {
            codCliente = new Integer(txtIDcliente.getText().toString());
        } catch (Exception e) {
            this.labelAlertaCliente.setVisible(true);
            return;
        }


        String horaPactadaDesde = jSpinner1.getValue().toString() + ":00";
        boolean delivery = jRBtnDelivery.isSelected();
        String horaPactadaHasta = null;
        if (delivery) {
            horaPactadaHasta = jSpinner2.getValue().toString() + ":00";

            if ((Integer) jSpinner1.getValue() >= (Integer) jSpinner2.getValue()) {
                JOptionPane.showMessageDialog(null, "Revise los horarios del delivery", "Atención", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
        } else {
            horaPactadaHasta = null;
        }
        Double montoTotal = new Double(this.tablaMontos.getValueAt(0, this.indiceTotal).toString());
        Double montoAbonado = new Double(this.tablaMontos.getValueAt(0, this.indiceSenia).toString());
        Double descuento = new Double(this.tablaMontos.getValueAt(0, this.indiceDescuento).toString());
        Double montoAdeudado = new Double(this.tablaMontos.getValueAt(0, this.indiceSaldo).toString());
        Double montoSubtotal= new Double(this.tablaMontos.getValueAt(0, this.indiceSubtotal).toString());
        //Es importante que esta verificacion se haga previo a persistir la orden
        DefaultTableModel modelo = (DefaultTableModel) tablaServicio.getModel();
        int cant = modelo.getRowCount();
        if (cant == 0) {
            this.labelErrorServicio.setVisible(true);
            return;
        }
        if (codOrden != null & codCliente != null) {
            try {
                //Va montoSubtotal en lugar de total porque yo consideraba el monto subtotal sin el descuento hecho, como monto total
                administradorOrden.persistirOrden(codCliente, txtFecha.getText(), fechaPactada, horaPactadaDesde, horaPactadaHasta,
                        montoSubtotal, montoAbonado, montoAdeudado, descuento, delivery, txtHora.getText(), observaciones);
            } catch (SQLException ex) {
                Logger.getLogger(AltaOrden.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
        for (int i = 0; i < cant; i++) {
            String nombreS = modelo.getValueAt(i, 0).toString();
            Integer cantidad = (Integer) modelo.getValueAt(i, 2);
            if (!nombreS.startsWith("S.E.")) {
                buscarServicioYpersistir(codOrden, nombreS, cantidad);
            }
        }
        this.persistirServiciosEsp();

        int opcion = JOptionPane.showConfirmDialog(null, "¿Desea Imprimir la orden?", "Impresión", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (opcion == JOptionPane.YES_OPTION) {

            Cliente cliente = null;
            ArrayList<ServicioContratado> serviciosContratados;
            ArrayList<ServicioContratado> serviciosEspContratados;
            try {
                Integer id = Integer.valueOf(this.idO.getText());
                Orden orden = this.administradorOrden.cargarOrden(id);
                cliente = this.administradorClientes.cargarCliente(orden.getCodCliente());
                //Listas con datos de los servicios contratados contienen precio, nombre, cantidad, y cod orden creo :P
                serviciosContratados = (ArrayList<ServicioContratado>) this.administradorOrden.mostrarTodosLosServiciosContratados(orden.getCodOrden());
                serviciosEspContratados = (ArrayList<ServicioContratado>) this.administradorOrden.mostrarTodosLosServiciosEspContratados(orden.getCodOrden());
                Imprimir_ticket impresion = new Imprimir_ticket();
                impresion.imprimir(orden, cliente, serviciosContratados, serviciosEspContratados);
            } catch (Exception e) {
                //JOptionPane.showMessageDialog(null,"No ha seleccionado ninguna orden");
            }
        }
        this.dispose();
    }//GEN-LAST:event_jBtnRegistrarActionPerformed

    void buscarServicioYpersistir(Integer codOrden, String nombreServicio, Integer cant) {
        ListIterator it = servicios.listIterator();
        while (it.hasNext()) {
            Servicio service = (Servicio) it.next();
            if (service.getNombre().equalsIgnoreCase(nombreServicio)) {
                try {
                    administradorOrden.persistirServicioDeOrden(codOrden, service, cant);
                } catch (SQLException ex) {
                    Logger.getLogger(AltaOrden.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    private void jBtnLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnLimpiarActionPerformed
        txtIDcliente.setText("");
        int cant = this.tablaServicio.getRowCount();
        DefaultTableModel modelo = (DefaultTableModel) this.tablaServicio.getModel();
        for (int i = 0; i < cant; i++) {
            modelo.removeRow(0);
        }
        this.txtApellido.setVisible(false);
        this.labelApellido.setVisible(false);
        this.txtNombre.setVisible(false);
        this.labelNombre.setVisible(false);
        this.jRBtnDelivery.setSelected(false);
        this.labelCel.setVisible(false);
        this.txtCel.setVisible(false);
        this.labelTel.setVisible(false);
        this.txtTel.setVisible(false);
        this.labelDireccion.setVisible(false);
        this.txtDir.setVisible(false);
        this.serviciosEspeciales.clear();
        this.txtAreaObservaciones.setText("");
        if (this.jSpinner2.isVisible()) {
            this.jSpinner2.setVisible(false);
            this.jLabel10.setVisible(false);
        }
        this.tablaTotalPendientes.setValueAt(0, inicio, valets);
        this.tablaTotalPendientes.setValueAt(0, inicio, planchados);
        iniciarTablaMontos();
    }//GEN-LAST:event_jBtnLimpiarActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        BuscarOrden buscarOrden = null;
        try {
            buscarOrden = new BuscarOrden(null, rootPaneCheckingEnabled);
        } catch (SQLException ex) {
            Logger.getLogger(AltaOrden.class.getName()).log(Level.SEVERE, null, ex);
        }
        buscarOrden.setVisible(false);
        this.setVisible(false);
    }//GEN-LAST:event_jButton4ActionPerformed

    private void cbServiciosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbServiciosActionPerformed
    }//GEN-LAST:event_cbServiciosActionPerformed

    private void jRBtnDeliveryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRBtnDeliveryActionPerformed
        if (this.jRBtnDelivery.isSelected()) {
            this.jLabel10.setVisible(true);
            this.jSpinner2.setVisible(true);
        } else {
            this.jLabel10.setVisible(false);
            this.jSpinner2.setVisible(false);
        }
    }//GEN-LAST:event_jRBtnDeliveryActionPerformed

    private void tablaMontosInputMethodTextChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_tablaMontosInputMethodTextChanged
    }//GEN-LAST:event_tablaMontosInputMethodTextChanged

    private void jBtnAgregarServicioFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jBtnAgregarServicioFocusGained
        // TODO add your handling code here:
    }//GEN-LAST:event_jBtnAgregarServicioFocusGained

    private void tablaMontosKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tablaMontosKeyPressed
    }//GEN-LAST:event_tablaMontosKeyPressed

    private void txtIDclienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtIDclienteActionPerformed
    }//GEN-LAST:event_txtIDclienteActionPerformed

    private void txtHoraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtHoraActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtHoraActionPerformed

    private void txtFechaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtFechaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtFechaActionPerformed

    private void idOActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_idOActionPerformed
    }//GEN-LAST:event_idOActionPerformed

    private void BtnQuitarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnQuitarActionPerformed
        DefaultTableModel modelo = (DefaultTableModel) this.tablaServicio.getModel();
        try {
            int fila = this.tablaServicio.getSelectedRow();
            String nombre = this.tablaServicio.getValueAt(fila, 0).toString();
            Integer cant = Integer.valueOf(this.tablaServicio.getValueAt(fila, 2).toString());
            if (nombre.startsWith("S.E.")) {
                this.serviciosEspeciales.remove(this.ServEsp(nombre));
            } else {
                modificarTablaTotalPendientes(nombre, cant);
            }
            modelo.removeRow(fila);
            this.calcularMontosTablaMontos();


        } catch (Exception e) {
        }

    }//GEN-LAST:event_BtnQuitarActionPerformed

    private void btnAbonaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAbonaActionPerformed

        try {
            Double monto = new Double(JOptionPane.showInputDialog("Ingrese la seña:").toString());
            if (monto < 0) {
                JOptionPane.showMessageDialog(null, "Valor Ingresado Inválido", "Seña Inválida", JOptionPane.PLAIN_MESSAGE);
                return;
            }
            DefaultTableModel modelo = (DefaultTableModel) this.tablaMontos.getModel();
            modelo.setValueAt(monto, 0, this.indiceSenia);
            this.calcularMontosTablaMontos();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Valor Ingresado Inválido", "Seña Inválida", JOptionPane.PLAIN_MESSAGE);
        }
    }//GEN-LAST:event_btnAbonaActionPerformed

    private void jDateChooser1FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jDateChooser1FocusGained
    }//GEN-LAST:event_jDateChooser1FocusGained

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            Integer valor = new Integer(JOptionPane.showInputDialog("Ingrese el porcentaje de descuento.\nEl mismo se descontará del Subtotal").toString());
            if (valor < 0 || valor > 100) {
                JOptionPane.showMessageDialog(null, "El porcentaje ingresado no es válido", "Porcentaje Inválido", JOptionPane.PLAIN_MESSAGE);
                return;
            }
            this.porcentajeDescuento = valor;
            this.calcularMontosTablaMontos();
        } catch (Exception e) {
        }

    }//GEN-LAST:event_jButton1ActionPerformed

    private void btnObservacionesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnObservacionesActionPerformed
        /* this.observaciones=JOptionPane.showInputDialog(null,"Ingrese las observaciones, recuerde que si ya ha ingresado observaciones previamente, estas se perderán.",
         "Observaciones",JOptionPane.YES_NO_OPTION);*/
    }//GEN-LAST:event_btnObservacionesActionPerformed

    private void txtAreaObservacionesKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtAreaObservacionesKeyReleased
        
        this.observaciones = this.txtAreaObservaciones.getText();
       
    }//GEN-LAST:event_txtAreaObservacionesKeyReleased

    private void txtAreaObservacionesKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtAreaObservacionesKeyTyped
        int cant = 99;
        String obs =txtAreaObservaciones.getText();
        if(obs.length() > cant){
            String recorte=obs.substring(inicio, cant);
            this.txtAreaObservaciones.setText(recorte);
       }
    }//GEN-LAST:event_txtAreaObservacionesKeyTyped
    /**
     * @param args the command line arguments
     */
    //public static void main(String args[]) {
        /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    /*        try {
     for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
     if ("Nimbus".equals(info.getName())) {
     javax.swing.UIManager.setLookAndFeel(info.getClassName());
     break;
     }
     }
     } catch (ClassNotFoundException ex) {
     java.util.logging.Logger.getLogger(AltaOrden.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
     } catch (InstantiationException ex) {
     java.util.logging.Logger.getLogger(AltaOrden.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
     } catch (IllegalAccessException ex) {
     java.util.logging.Logger.getLogger(AltaOrden.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
     } catch (javax.swing.UnsupportedLookAndFeelException ex) {
     java.util.logging.Logger.getLogger(AltaOrden.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
     }
     //</editor-fold>

     /* Create and display the dialog */
    /* java.awt.EventQueue.invokeLater(new Runnable() {
     public void run() {
     AltaOrden dialog = null;
     try {
     dialog = new AltaOrden(new javax.swing.JFrame(), true);
     } catch (SQLException ex) {
     Logger.getLogger(AltaOrden.class.getName()).log(Level.SEVERE, null, ex);
     }
     dialog.addWindowListener(new java.awt.event.WindowAdapter() {
     @Override
     public void windowClosing(java.awt.event.WindowEvent e) {
     System.exit(0);
     }
     });
     dialog.setVisible(true);
     }
     });
     }*/
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BtnQuitar;
    private javax.swing.JButton btnAbona;
    private javax.swing.JButton btnObservaciones;
    private javax.swing.JComboBox cbServicios;
    private javax.swing.JTextField idO;
    private javax.swing.JButton jBtnAgregarCliente;
    private javax.swing.JButton jBtnAgregarServicio;
    private javax.swing.JButton jBtnBuscarCliente;
    private javax.swing.JButton jBtnLimpiar;
    private javax.swing.JButton jBtnRegistrar;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton4;
    private com.toedter.calendar.JDateChooser jDateChooser1;
    private javax.swing.JDialog jDialog1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JRadioButton jRBtnDelivery;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JSpinner jSpinner1;
    private javax.swing.JSpinner jSpinner2;
    private javax.swing.JTable jTable2;
    private javax.swing.JLabel labelAlertaCliente;
    private javax.swing.JLabel labelApellido;
    private javax.swing.JLabel labelCantidad;
    private javax.swing.JLabel labelCel;
    private javax.swing.JLabel labelCliente;
    private javax.swing.JLabel labelDireccion;
    private javax.swing.JLabel labelErrorServicio;
    private javax.swing.JLabel labelNombre;
    private javax.swing.JLabel labelObservaciones;
    private javax.swing.JLabel labelTel;
    private javax.swing.JSpinner spinnerCantidad;
    private javax.swing.JTable tablaMontos;
    private javax.swing.JTable tablaPendientes;
    private javax.swing.JTable tablaServicio;
    private javax.swing.JTable tablaTotalPendientes;
    private javax.swing.JTextField txtApellido;
    private javax.swing.JTextArea txtAreaObservaciones;
    private javax.swing.JTextField txtCel;
    private javax.swing.JTextField txtDir;
    private javax.swing.JTextField txtFecha;
    private javax.swing.JTextField txtHora;
    private javax.swing.JTextField txtIDcliente;
    private javax.swing.JTextField txtNombre;
    private javax.swing.JTextField txtTel;
    // End of variables declaration//GEN-END:variables

    private void persistirServiciosEsp() {
        ListIterator itSE = this.serviciosEspeciales.listIterator();
        while (itSE.hasNext()) {
            ServicioEspecialContratado servEsp = (ServicioEspecialContratado) itSE.next();
            try {
                this.administradorOrden.persistirServEspDeOrden(servEsp);
            } catch (Exception e) {
            }
        }
    }

    private void cargarPendientes() {
        DefaultTableModel modelo = (DefaultTableModel) this.tablaPendientes.getModel();
        int cantCol = modelo.getColumnCount();
        String fechaEntrega = null;
        for (int i = 1; i < cantCol; i++) {
            try {
                fechaEntrega = tablaPendientes.getColumnName(i);
                int prendaLavado = this.administradorOrden.getCantPendientes(fechaEntrega, TipoServicio.Planchado.toString());
                modelo.setValueAt(prendaLavado, 0, i);
                int valetLavado = this.administradorOrden.getCantPendientes(fechaEntrega, TipoServicio.Valets.toString());
                modelo.setValueAt(valetLavado, 1, i);
                int deliverys = this.administradorOrden.getCantDeliverysPendientesParaDia(fechaEntrega);
                modelo.setValueAt(deliverys, 2, i);
            } catch (Exception ex) {
                Logger.getLogger(AltaOrden.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private void modificarTablaTotalPendientes(String nombre, Integer cant) {
        Integer cantidad;
        for (Servicio servicio : servicios) {
            if (servicio.getNombre().equalsIgnoreCase(nombre)) {
                if (servicio.getTipoServicio().equalsIgnoreCase(TipoServicio.Valets.toString())) {
                    cantidad = Integer.valueOf(this.tablaTotalPendientes.getValueAt(0, valets).toString());
                    this.tablaTotalPendientes.setValueAt(cantidad - cant, 0, valets);
                } else if (servicio.getTipoServicio().equalsIgnoreCase(TipoServicio.Planchado.toString())) {
                    cantidad = Integer.valueOf(this.tablaTotalPendientes.getValueAt(0, planchados).toString());
                    this.tablaTotalPendientes.setValueAt(cantidad - cant, 0, planchados);
                }
                return;
            }
        }
    }
}
